import React, { useState, useRef, useEffect } from 'react';
import styled from '@emotion/styled';
import StepNode from './StepNode';
import { Button } from 'antd';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import AgentService from '@/modules/Agent';
import { checkRecordPoint, createRecordPoint, getHumanflowSteps, postHumanflowStep } from '@/api';
import { useStream, IStream } from '@/views/Context/StreamContext';
import Message from '@/utils/message';
import MessageEnum from '@/utils/MessageEnum';
import { useTranslation } from 'react-i18next';
import { sendHumanStepDetail, onHumanStepDetail } from '@/utils/lib';
import { use } from 'i18next';

interface HumanflowStepsProps {
	id: number;
	humanflowId: number;
	content: string;
	isDot: boolean;
	status: string; // done | doing | not-started
	name: string;
	tips: string;
}

interface HumanflowProps {
	steps?: HumanflowStepsProps[];
	onCurTips?: (tips: string) => void;
}

const HumanflowContainer = styled.div`
	width: 100%;
	height: 50px;
	position: fixed;
	top: 50px;
	display: flex;
	justify-content: center;
	align-items: center;
	background: #fff;
    z-index: 98;
`;

const HumanflowWrapper = styled.div`
	width: 100%;
	height: 50px;
	max-width: 1280px;
	min-width: 1024px;
	position: relative;
	overflow: hidden;
	font-size: 11px;
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 0 150px 0 50px;

	.humanflow-steps {
		display: flex;
		align-items: center;
		width: fit-content;
		overflow: hidden;
		justify-content: flex-start;
		height: 100%;
	}
	.humanflow-step {
		display: flex;
		align-items: center;
		justify-content: center;
		min-width: 135px;
		height: 100%;
	}
`;

const LeftButton = styled(Button)`
	position: absolute;
	left: 10px;
	background: #ffffff;
	z-index: 2;

	&:hover {
		background: #ffffff;
	}
	&:focus {
		background: #ffffff;
	}
`;

const RightButton = styled(Button)`
	position: absolute;
	right: 110px;
	background: #ffffff;
	z-index: 2;

	&:hover {
		background: #ffffff;
	}
	&:focus {
		background: #ffffff;
	}
`;
// 下一步按钮
const NextButton = styled(Button)`
	position: absolute;
	right: 10px;
	background: #ffffff;
	z-index: 1;

	&:hover {
		background: #ffffff;
	}

	&:focus {
		background: #ffffff;
	}
`;
// 已完成label
const CompletedSpan = styled.span`
	position: absolute;
	right: 10px;
	z-index: 1;
`;



const Humanflow = (props: HumanflowProps) => {
	const { t } = useTranslation();
	const { steps = [], onCurTips } = props;
	const [localSteps, setLocalSteps] = useState([...steps]);
	const [currentStep, setCurrentStep] = useState(0);
	const [visible, setVisible] = useState(false);
	// agent streams role: "agent"
	const [agentStreams, setAgentStreams] = useState<IStream[]>([]);
	// left button disable
	const [leftButtonDisable, setLeftButtonDisbale ] = useState(true);
	// right button disable
	const [rightButtonDisable, setRightButtonDisbale ] = useState(false);
	const scrollRef = useRef(null);
	const { recordPoint, setRecordPoint, smallStream } = useStream();
	// is first agent
	const [isFirstAgent, setIsFirstAgent] = useState(false);

	useEffect(() => {
		// 可以全部显示时，隐藏左右按钮
		const scrollContainer: any = scrollRef.current;
		if (scrollContainer.scrollWidth - scrollContainer.clientWidth > 0) {
			setVisible(true);
		}
		onCurTips && onCurTips(localSteps[currentStep].tips);
		onHumanStepDetail((data: any) => {
			console.log('onHumanStepDetail data', data);
			const { step } = data?.data || {};
			// 更新已完成的步骤
			updateLocalStepStatus(step);
		});
		getHumanflowSteps(AgentService.sessionId).then((res) => {
			if (res.data.length > 0) {
				const step = res.data[res.data.length - 1].stepContent || {};
				updateLocalStepStatus(step.id);
			}
			console.log('getHumanflowSteps', res);
		}).catch((error) => {
			console.log('getHumanflowSteps error', error);
		});
	}, []);

	useEffect(() => {
		if (formatTips(localSteps[currentStep].status) === 'doing') {
			onCurTips && onCurTips(formatTips(localSteps[currentStep].tips));
		}
	}, [AgentService.customerVariableList, AgentService.businessVariableList]);

	useEffect(() => {
		const streams = smallStream().filter((stream: any) => stream.role === 'agent' && !stream.isRobot);
		console.log('agentStreams', streams);
		setAgentStreams(streams);
		if (AgentService.isIMSession) {
			const agents = AgentService.sessionMembers?.filter(item => item.role === 'agent');
			setIsFirstAgent(agents[0]?.id === AgentService.user?.clientId);
		} else {
			setIsFirstAgent(streams[0]?.clientId === AgentService.user?.clientId);
		}
	}, [smallStream()]);

	useEffect(() => {
		const checkPointAsync = async (content: string) => {
			// 如果没有录制ID，不进行打点
			if (!recordPoint().recordingId) {
				return;
			}
			try {
				const count = await getRecordPointCount() || 0;
				console.log('checkPointAsync', count);
				if (count === 0) {
					checkPoint(content);
				}
			} catch (error) {
				console.log(error);
			}
		}
		// 如果是第一个步骤，打点
		if (agentStreams[0]?.clientId === AgentService.user?.clientId) {
			if (localSteps[0].isDot && localSteps[0].status === 'doing') {
				checkPointAsync(localSteps[0].name);
			}
		}
	}, [agentStreams[0]]);

	const handleLeftScroll = () => {
		setRightButtonDisbale(false);
		const scrollContainer: any = scrollRef.current;
		if (scrollContainer.scrollLeft > 0) {
			scrollContainer.scrollLeft -= 135; // 每次滚动135像素
			if (scrollContainer.scrollLeft <= 0) {
				setLeftButtonDisbale(true);
			}
		} else {
			scrollContainer.scrollLeft = 0;
			setLeftButtonDisbale(true);
		}
	};

	const handleRightScroll = () => {
		setLeftButtonDisbale(false);
		const scrollContainer: any = scrollRef.current;
		if (scrollContainer.scrollLeft < scrollContainer.scrollWidth - scrollContainer.clientWidth) {
			scrollContainer.scrollLeft += 135; // 每次滚动135像素
			if (scrollContainer.scrollLeft >= scrollContainer.scrollWidth - scrollContainer.clientWidth) {
				setRightButtonDisbale(true);
			}
		} else {
			setRightButtonDisbale(true);
		}
	};

	const checkScrollButton = () => {
		const scrollContainer: any = scrollRef.current;
		if (scrollContainer.scrollLeft <= 0) {
			setLeftButtonDisbale(true);
		} else {
			setLeftButtonDisbale(false);
		}
		if (scrollContainer.scrollLeft >= scrollContainer.scrollWidth - scrollContainer.clientWidth) {
			setRightButtonDisbale(true);
		} else {
			setRightButtonDisbale(false);
		}
	}

	const handleNextStep = () => {
		const newSteps = [...localSteps];
		for (let i = 0; i < newSteps.length; i++) {
			if (newSteps[i].status === 'doing') {
				newSteps[i].status = 'done';
				notifyRemoteStepDone(newSteps[i]);
				if (i >= newSteps.length - 1) {
					onCurTips && onCurTips('');
					break;
				}

				newSteps[i + 1].status = 'doing';
				setCurrentStep(i + 1);
				onCurTips && onCurTips(formatTips(newSteps[i + 1].tips));
				if (newSteps[i + 1].isDot) {
					checkPoint(newSteps[i + 1].name);
				}
				// 当被遮挡时滚动到当前步骤
				const scrollContainer: any = scrollRef.current;
				const currentStepNode = document.getElementById(`step-node-${newSteps[i + 1].id}`);
				if (currentStepNode) {
					const left = currentStepNode.offsetLeft;
					const right = currentStepNode.offsetLeft + currentStepNode.offsetWidth;
					if (left < scrollContainer.scrollLeft) {
						scrollContainer.scrollLeft = left;
					} else if (right > scrollContainer.scrollLeft + scrollContainer.clientWidth) {
						scrollContainer.scrollLeft = right - scrollContainer.clientWidth;
					}
					checkScrollButton();
				}
				break;
			}
		}
		setLocalSteps(newSteps);
	};

	const formatTips = (tips: string) => {
		if (!tips) return '';
		const regex = /{{(.*?)}}/g;
		const matches = tips.match(regex);
		if (!matches) return tips;
		let newTips = tips;
		matches.forEach((match: string) => {
			// {{客户信息_customer_头像_431}}
			const key = match.replace('{{', '').replace('}}', '');
			const [type, role, name, id] = key.split('_');
			if (type === '客户信息') {
				const value = AgentService.customerVariableList.find(item => String(item.id) === id)?.value || '';
				newTips = newTips.replace(match, value);
			} else if (type === '业务信息') {
				const value = AgentService.businessVariableList.find(item => String(item.id) === id)?.value || '';
				newTips = newTips.replace(match, value);
			}
		});
		return newTips;
	}

	const checkPoint = async (name: string) => {
		// 如果没有录制ID，不进行打点
		if (!recordPoint().recordingId) {
			console.log('checkPoint', recordPoint());
			
			return;
		}
		try {
			const { data } = await checkRecordPoint(recordPoint().recordingId);
			if (data.code === '0000') {
				if (data.data.count < 50) {
					setRecordPoint({ ...recordPoint(), timePoint: data.data.timePoint, content: name.trim() });

					await submitPoint();
				}
			}
		} catch (error) {
			console.log(error);
		}
	};

	const submitPoint = async () => {
		try {
			const { data } = await createRecordPoint(recordPoint());
			if (data.code === '0000') {
				// Message.normal(MessageEnum.RECORD_POINT_SUCCESS);
			} else if (data.code === '1401') {
				Message.normal(MessageEnum.RECORD_POINT_MAX);
			} else if (data.code === '1404') {
				Message.normal(MessageEnum.RECORD_FILE_NOT_EXIST);
			} else if (data.code === '1405') {
				Message.normal(`${t('system-recording-file-storage-failed')}`);
			} else if (data.code === '1406') {
				Message.normal(`${t('system-recording-file-storage-interruption')}`);
			} else {
				Message.normal(MessageEnum.RECORD_POINT_FAILED);
			}
		} catch (error) {
			Message.normal(MessageEnum.RECORD_POINT_FAILED);
		}
	};

	const updateLocalStepStatus = (step: number) => {
		const newSteps = [...localSteps];
		for (let i = 0; i < newSteps.length; i++) {
			if (newSteps[i].id === step) {
				newSteps[i].status = 'done';
				if (i >= newSteps.length - 1) {
					onCurTips && onCurTips('');
					break;
				}

				newSteps[i + 1].status = 'doing';
				setCurrentStep(i + 1);
				onCurTips && onCurTips(formatTips(newSteps[i + 1].tips));
				// 当被遮挡时滚动到当前步骤
				const scrollContainer: any = scrollRef.current;
				const currentStepNode = document.getElementById(`step-node-${newSteps[i + 1].id}`);
				if (currentStepNode) {
					const left = currentStepNode.offsetLeft;
					const right = currentStepNode.offsetLeft + currentStepNode.offsetWidth;
					if (left < scrollContainer.scrollLeft) {
						scrollContainer.scrollLeft = left;
					} else if (right > scrollContainer.scrollLeft + scrollContainer.clientWidth) {
						scrollContainer.scrollLeft = right - scrollContainer.clientWidth;
					}
				}
				break;
			} else {
				newSteps[i].status = 'done';
			}
		}
		setLocalSteps(newSteps);
	};

	const notifyRemoteStepDone = (step: HumanflowStepsProps) => {
		if (agentStreams?.length > 1) {
			sendHumanStepDetail(
				{humanflowId: step.humanflowId, step: step.id},
				'agents',
			).then((res) => {
				console.log('sendHumanStepDetail', res);
			}).catch((error) => {
				console.log('sendHumanStepDetail error', error);
			});
		}
		// { humanStepId: number; content: string; sessionId: string; bizScenarioId: number }
		const data = {
			humanStepId: step.id,
			content: step.content,
			sessionId: AgentService.sessionId,
			bizScenarioId: AgentService.bizScenarioId,
		};
		postHumanflowStep(data)
			.then((res) => {
				console.log('postHumanflowStep', res);
			})
			.catch((error) => {
				console.log('postHumanflowStep error', error);
			});
	}

	const getRecordPointCount = async () => {
		try {
			const { data } = await checkRecordPoint(recordPoint().recordingId);
			if (data.code === '0000') {
				console.log(data.data.count);
				return data.data.count;
			} else {
				return 0;
			}
		} catch (error) {
			console.error(error);
			return 0;
		}
		
	};

	return (
		<HumanflowContainer style={{display: ['agentManagement', 'serviceRecord'].includes(AgentService.configure.currentTab) ? 'none' : 'block'}}>
			<HumanflowWrapper>
				{visible && <LeftButton shape="circle" icon={<LeftOutlined style={{ color: '#000' }} />} disabled={leftButtonDisable} onClick={handleLeftScroll}></LeftButton>}
				<div className="humanflow-steps" ref={scrollRef}>
					{localSteps.map((step, index) => (
						<div key={index} className={`humanflow-step ${step.isDot ? 'dot' : ''}`}>
							<StepNode name={step.name} status={step.status} isLast={index === localSteps.length - 1} id={step.id} />
						</div>
					))}
				</div>
				{visible && <RightButton shape="circle" icon={<RightOutlined style={{ color: '#000' }} />} disabled={rightButtonDisable} onClick={handleRightScroll}></RightButton>}
				{/* 下一步按钮 */}
				{isFirstAgent && localSteps[localSteps.length - 1].status !== 'done' && <NextButton onClick={handleNextStep}>{currentStep === localSteps.length - 1 ? t('done') : t('next-step')}</NextButton>}
				{isFirstAgent && localSteps[localSteps.length - 1].status === 'done' && <CompletedSpan>{t('completed')}</CompletedSpan>}
			</HumanflowWrapper>
		</HumanflowContainer>
	);
};

export default Humanflow;
